#!/usr/bin python3
# -*- coding: utf-8 -*-
"""  用户相关操作service   """
import uuid
from gtm_server.dao.user import register_user_dao
from gtm_server.dao.user import get_all_account
from gtm_server.common.constant import TaskStatusKeys
from gtm_server.common.database_pg import DBPool


def register_user(user_data):
    """
    用户注册
    Args:
        user_data: User data
            {
                account:"",
                name:"",
                password:"",
                company:"",
                part:"",
                title:""
            }
    """
    # 提取用户注册的数据
    id = uuid.uuid4()
    account = user_data.get("account")
    name = user_data.get("name")
    password = user_data.get("password")
    company = user_data.get("company")
    part = user_data.get("part")
    title = user_data.get("title")

    # 用户账户是否存在验证
    result = check_account(account)
    if result is False:
        return TaskStatusKeys.FAILED

    with DBPool().get_session() as session:
        result = register_user_dao(session=session,
                                   id=id,
                                   account=account,
                                   name=name,
                                   password=password,
                                   company=company,
                                   part=part,
                                   title=title)

    return result


def check_account(account):
    """
    检查账号是否已经存在
    """
    with DBPool().get_session() as session:
        users = get_all_account(session)

    if users is None:
        return True
    for user in users:
        if users == TaskStatusKeys.FAILED or account == user.account:
            return False



